/*
 * @lc app=leetcode.cn id=2 lang=javascript
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
// 在新链表上相加,要注意最后一个进位
var addTwoNumbers = function(l1, l2) {
  let head = tail = null
  let carry = 0
  while (l1 || l2) {
    let n1 = l1 ? l1.val : 0
    let n2 = l2 ? l2.val : 0

    let total = n1 + n2 + carry

    if (!head) {
      head = tail = new ListNode(total % 10)
    } else {
      tail.next = new ListNode(total % 10)
      tail = tail.next
    }

    carry = Math.floor(total / 10)

    if (l1) {
      l1 = l1.next
    }
    if (l2) {
      l2 = l2.next
    }
  }
  if (carry) {
    tail.next = new ListNode(carry)
  }
  return head
}
// @lc code=end
// 在原链表上相加
// var addTwoNumbers = function(l1, l2) {
//   let jin = 0
//   let point1 = l1
//   let point2 = l2
//   while (point1) {
//     // point1 比 point2短，并且遇到交接的地方
//     if (!point1.next && point2 && point2.next) {
//       let total = point1.val + point2.val + jin
//       if (total >= 10) {
//         jin = Math.floor(total / 10)
//         point1.val = (total % 10)
//       } else {
//         point1.val = total
//         jin = 0
//       }
//       point1.next = point2.next
//       point2 = null
//       point1 = point1.next
//     }
//     // poin2没了，point1有进位
//     if (!point2) {
//       if (!jin) return l1
//       let total = point1.val + jin
//       if (total >= 10) {
//         jin = Math.floor(total / 10)
//         point1.val = (total % 10)
//         if (!point1.next) {
//           point1.next = new ListNode(jin)
//           return l1
//         }
//       } else {
//         point1.val = total
//         return l1
//       }
//       point1 = point1.next
//     } else {
//       let total = point1.val + point2.val + jin
//       if (total >= 10) {
//         jin = Math.floor(total / 10)
//         point1.val = (total % 10)
//         if (!point1.next) {
//           point1.next = new ListNode(jin)
//           return l1
//         }
//       } else {
//         point1.val = total
//         jin = 0
//       }
//       point2 = point2.next
//       point1 = point1.next
//     }
//   }
//   return l1
// };

